package com.iqiyi.pps.epg.web.timer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.kiwi.utils.Configuration;
import com.iqiyi.pps.epg.core.model.channel.ChannelBase;
import com.iqiyi.pps.epg.core.model.channel.ChannelBoss;
import com.iqiyi.pps.epg.core.model.channel.ChannelConfig;
import com.iqiyi.pps.epg.core.model.channel.ChannelLog;
import com.iqiyi.pps.epg.core.model.control.PlatformControl;
import com.iqiyi.pps.epg.core.model.program.ProgramData;
import com.iqiyi.pps.epg.core.model.remind.MailRemind;
import com.iqiyi.pps.epg.core.model.stream.LiveChannelStream;
import com.iqiyi.pps.epg.core.service.broadcast.BroadcastControlService;
import com.iqiyi.pps.epg.core.service.channel.ChannelService;
import com.iqiyi.pps.epg.core.service.notifymail.NotifyMailService;
import com.iqiyi.pps.epg.core.service.program.ProgramService;
import com.iqiyi.pps.epg.core.service.remind.MailRemindService;
import com.iqiyi.pps.epg.core.service.stream.LiveChannelStreamService;
import com.iqiyi.pps.epg.core.service.stream.LiveStreamService;
import com.iqiyi.pps.epg.core.utils.ApiHttpRequestUtil;
import com.iqiyi.pps.epg.core.utils.Constants;
import com.iqiyi.pps.epg.core.utils.DateTimeUtil;
import com.iqiyi.pps.epg.core.utils.MailContentUtil;
import com.iqiyi.pps.epg.core.utils.mail.MailConstant;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by karkarrotxu on 2015/9/1.
 */
public class AutoBroadCastControlTrigger {
    private static Logger logger = LoggerFactory.getLogger(AutoBroadCastControlTrigger.class);
    @Autowired
    private BroadcastControlService broadcastControlService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private MailRemindService mailRemindService;
    @Autowired
    private ProgramService programService;
    @Autowired
    private LiveChannelStreamService liveChannelStreamService;
    @Autowired
    private LiveStreamService liveStreamService;
    @Autowired
    private NotifyMailService notifyMailService;

    private List<Integer> platforms = null;
    public static long ONLINE_GAP_TIME = Configuration.getLong("online.gap.time") * 1000L;
    public static long ONLINE_TRANSITION_TIME = Configuration.getLong("online.transition.time") * 1000L;
    public static long OFFLINE_GAP_TIME = Configuration.getLong("offline.gap.time") * 1000L;
    public static long FIND_OFFLINE_GAP_TIME = OFFLINE_GAP_TIME + DateTimeUtil.DAY_TIME;
    public static long DELETE_GAP_TIME = Configuration.getLong("delete.gap.time") * 1000L;
    public static long FIND_DELETE_GAP_TIME = DELETE_GAP_TIME + 86400000L;
    public static long DELETE_NONCYCLIAL_GAP_TIME = Configuration.getLong("delete.noncyclical.gap.time") * 1000L;
    public static long FIND_NONCYCLICAL_DELETE_GAP_TIME = DELETE_NONCYCLIAL_GAP_TIME + 86400000L;

    public void init() {
        String load = Configuration.getString("online.auto.platforms").replaceAll(";", ",");

        platforms = JSON.parseArray(load, Integer.class);
    }

    public void task() {
        init();
        try {
            autoOnline();
        } catch (Exception e) {
            logger.error("[AutoBroadCastControlTrigger][autoOnline][exception={}]", e);
        }
        try {
            autoOffLine();
        } catch (Exception e) {
            logger.error("[AutoBroadCastControlTrigger][autoOffLine][exception={}]", e);
        }
        try {
            autoStreamDelete();
            //  autoDelete();
        } catch (Exception e) {
            logger.error("[AutoBroadCastControlTrigger][autoDelete][exception={}]", e);
        }
    }

    public void autoOnline() {
        logger.info("[AutoBroadCastControlTrigger][autoOnline] start");
        long startTime = System.currentTimeMillis();
        long minCheckTime = startTime + (ONLINE_GAP_TIME);
        long maxCheckTime = startTime + (ONLINE_GAP_TIME + 2 * ONLINE_TRANSITION_TIME);
        List<Long> channelIds = channelService.fetchChannelList(DateTimeUtil.transLongFormat(minCheckTime), DateTimeUtil.transLongFormat(maxCheckTime));
        logger.info("[AutoBroadCastControlTrigger][autoOnline][ready check ] size" + channelIds.size());
        if (channelIds.size() > 0) {
            Map<Long, Integer> resultMap = broadcastControlService.fetchPlatControls(ChannelBase.LIVE_TYPE_LS);
            ChannelBoss channelBoss = null;
            boolean isFree = false;
            for (Long channelId : channelIds) {
                Integer onlineNum = resultMap.get(channelId);
                if (onlineNum != null && onlineNum > 0) {
                    continue;
                }
                channelBoss = channelService.getChannelBoss(channelId);
                List<LiveChannelStream> liveChannelStreamList = liveChannelStreamService.getByFatherId(channelId);
                boolean hasEncode = false;
                for (LiveChannelStream liveChannelStream : liveChannelStreamList) {
                    if (liveChannelStream.getStatus() == 1) {
                        hasEncode = true;
                        break;
                    }
                }
                if (!hasEncode) {
                    logger.info("[ autoOnline check  has no live_channel_stream encode] channelId :" + channelId);
                    continue;
                }
                //  channelBoss
                isFree = channelBoss != null && ProgramData.FREE.equals(channelBoss.getStatus());
                if (onlineNum == null) {
                    doCreateDefaultPlatformControls(channelId, isFree);
                } else if (onlineNum == 0) {
                    updateOnlineControls(channelId);
                }
            }
        }
        long endTime = System.currentTimeMillis();
        logger.info("[AutoBroadCastControlTrigger][autoOnline] end" + (endTime - startTime));
    }

    public void autoOffLine() {
        logger.info("[AutoBroadCastControlTrigger][autoOffLine] start");
        long startTime = System.currentTimeMillis();
        Map<Long, Integer> resultMap = broadcastControlService.fetchPlatControls(ChannelBase.LIVE_TYPE_LS);
        logger.info("[AutoBroadCastControlTrigger][autoOffLine][ready check] " + resultMap.size());
        String endDate = DateTimeUtil.transLongFormat(startTime + DateTimeUtil.DAY_TIME);
        String startDate = DateTimeUtil.transLongFormat(startTime - FIND_OFFLINE_GAP_TIME);
        List<Order> orderList = new ArrayList<Order>();
        orderList.add(Order.asc("startPlayTime"));
        List<Criterion> cList = new ArrayList<Criterion>();
        cList.add(Restrictions.eq("deleteFlag", 0));
        cList.add(Restrictions.gt("qipuId", 0L));
        cList.add(Restrictions.and(Restrictions.le("startPlayTime", Timestamp.valueOf(endDate)), Restrictions.ge("stopPlayTime", Timestamp.valueOf(startDate))));
        List<Criterion> usedList = new ArrayList<Criterion>();
        List<ProgramData> programDataList = null;
        ChannelBase channelBase = null;
        for (Map.Entry<Long, Integer> entry : resultMap.entrySet()) {
            if (entry.getValue() > 0) {
                channelBase = channelService.getChannelBase(entry.getKey());
                if (checkSkipCheckOffLine(channelBase.getAddTime().getTime(), startTime)) {
                    continue;
                }
                usedList.clear();
                usedList.addAll(cList);
                usedList.add(Restrictions.eq("fatherId", entry.getKey().intValue()));
                programDataList = programService.queryDataByCriterion(usedList, orderList, 20);
                logger.info("[AutoBroadCastControlTrigger][autoOffLine] programDataList :" + (programDataList == null ? 0 : programDataList.size()));
                if (programDataList == null || programDataList.isEmpty()) {
                    updateOffControls(entry.getKey());
                } else {
                    int findNum = programDataList.size();
                    if (findNum > 0) {
                        ProgramData program = programDataList.get(findNum - 1);
                        if (program.getStopPlayTime().getTime() <= startTime - OFFLINE_GAP_TIME) {
                            updateOffControls(entry.getKey());
                        }
                    }
                }
            }
        }
        long endTime = System.currentTimeMillis();
        logger.info("[AutoBroadCastControlTrigger][autoOffLine] end" + (endTime - startTime));
    }

    private boolean checkSkipCheckDelete(long channelCreateTime, long sysCheckTime, boolean cyclial) {
        return cyclial ? channelCreateTime + DELETE_GAP_TIME > sysCheckTime : channelCreateTime + DELETE_NONCYCLIAL_GAP_TIME > sysCheckTime;
    }


    private boolean checkSkipCheckOffLine(long channelCreateTime, long sysCheckTime) {
        return channelCreateTime + OFFLINE_GAP_TIME > sysCheckTime;
    }


    public void autoDelete() {
        logger.info("[AutoBroadCastControlTrigger][autoDelete] start");
        long startTime = System.currentTimeMillis();
        Map<Long, Integer> resultMap = broadcastControlService.fetchPlatControls(ChannelBase.LIVE_TYPE_LS);
        logger.info("[AutoBroadCastControlTrigger][autoDelete][ready check][broadcast control num] " + resultMap.size());
        List<Criterion> expressionList = new ArrayList<Criterion>();
        expressionList.add(Restrictions.eq("liveType", 2));
        expressionList.add(Restrictions.gt("qipuId", 0L));
        expressionList.add(Restrictions.ne("isEnable", -1));
        List<ChannelBase> filterChannelBaseList = channelService.findChannelBaseList(expressionList);
        logger.info("[AutoBroadCastControlTrigger][autoDelete][ready check][channelBase num]" + filterChannelBaseList.size());

        String endDate = DateTimeUtil.transLongFormat(startTime + DateTimeUtil.DAY_TIME);
        String startDate = DateTimeUtil.transLongFormat(startTime - FIND_DELETE_GAP_TIME);
        String noncyclicalStartDate = DateTimeUtil.transLongFormat(startTime - FIND_NONCYCLICAL_DELETE_GAP_TIME);
        List<Order> orderList = new ArrayList<Order>();
        orderList.add(Order.asc("startPlayTime"));
        List<Criterion> cList = new ArrayList<Criterion>();
        cList.add(Restrictions.eq("deleteFlag", 0));
        cList.add(Restrictions.gt("qipuId", 0L));
        List<Criterion> usedList = new ArrayList<Criterion>();
        List<ProgramData> programDataList = null;

        SimpleExpression previousExpression = null;

        for (ChannelBase channelBase : filterChannelBaseList) {
            if (!resultMap.containsKey(channelBase.getId()) || resultMap.get(channelBase.getId()).intValue() == 0) {
                if (checkSkipCheckDelete(channelBase.getAddTime().getTime(), startTime, channelBase.getCyclical() == 1)) {
                    continue;
                }
                usedList.clear();

                cList.remove(previousExpression);
                previousExpression = Restrictions.ge("stopPlayTime", Timestamp.valueOf(
                        channelBase.getCyclical() == 1 ? startDate : noncyclicalStartDate));
                cList.add(previousExpression);

                usedList.addAll(cList);
                usedList.add(Restrictions.eq("fatherId", channelBase.getId().intValue()));
                programDataList = programService.queryDataByCriterion(usedList, orderList, 20);
                if (programDataList == null || programDataList.size() == 0) {
                    doSystemDeleteChannel(channelBase);
                } else {
                    checkDeleteRemind(startTime, channelBase, programDataList);
                }
            }
        }

        long endTime = System.currentTimeMillis();
        logger.info("[AutoBroadCastControlTrigger][autoDelete] end" + (endTime - startTime));
    }

    public void autoStreamDelete() {
        logger.info("[AutoBroadCastControlTrigger][autoStreamDelete] start");
        long startTime = System.currentTimeMillis();
        Map<Long, Integer> resultMap = liveChannelStreamService.fetchChannelStream(ChannelBase.LIVE_TYPE_LS);
        List<Criterion> expressionList = new ArrayList<Criterion>();
        expressionList.add(Restrictions.eq("liveType", 2));
        expressionList.add(Restrictions.gt("qipuId", 0L));
        expressionList.add(Restrictions.ne("isEnable", -1));
        List<ChannelBase> filterChannelBaseList = channelService.findChannelBaseList(expressionList);
        logger.info("[AutoBroadCastControlTrigger][autoStreamDelete][ready check][channelBase num]" + filterChannelBaseList.size());
        String endDate = DateTimeUtil.transLongFormat(startTime + DateTimeUtil.DAY_TIME);
        String startDate = DateTimeUtil.transLongFormat(startTime - FIND_DELETE_GAP_TIME);
        String noncyclicalStartDate = DateTimeUtil.transLongFormat(startTime - FIND_NONCYCLICAL_DELETE_GAP_TIME);
        List<Order> orderList = new ArrayList<Order>();
        orderList.add(Order.asc("startPlayTime"));
        List<Criterion> cList = new ArrayList<Criterion>();
        cList.add(Restrictions.eq("deleteFlag", 0));
        cList.add(Restrictions.gt("qipuId", 0L));
        List<Criterion> usedList = new ArrayList<Criterion>();
        List<ProgramData> programDataList = null;

        SimpleExpression defaultPreviousExpression = Restrictions.ge("stopPlayTime", Timestamp.valueOf(startDate));
        SimpleExpression nonCyclicalPreviousExpression = Restrictions.ge("stopPlayTime", Timestamp.valueOf(noncyclicalStartDate));
        String errorMsg = "流在编码，不能删除";
        for (ChannelBase channelBase : filterChannelBaseList) {
            if (resultMap.containsKey(channelBase.getId())) {
                usedList.clear();
                usedList.addAll(cList);
                usedList.add(channelBase.getCyclical() == 1 ? defaultPreviousExpression : nonCyclicalPreviousExpression);
                usedList.add(Restrictions.eq("fatherId", channelBase.getId().intValue()));
                programDataList = programService.queryDataByCriterion(usedList, orderList, 20);
                if ( programDataList.size() == 0) {
                    if (resultMap.get(channelBase.getId()) > 0) {
                        doSendStreamEncodeMail(channelBase,errorMsg );
                    }else{
                        doSystemDeleteStream(channelBase);
                    }
                }
            }
        }

        long endTime = System.currentTimeMillis();
        logger.info("[AutoBroadCastControlTrigger][autoStreamDelete] end" + (endTime - startTime));
    }

    private PlatformControl createDefault(long channelId, int platform, long currentTime) {
        PlatformControl control = null;
        control = new PlatformControl();
        control.setFatherId(channelId);
        control.setPlayPlatform(platform);
        control.setIsDownloadAllowed(1);
        control.setIsDrm(1);
        control.setIsShareAllowed(1);
        control.setIsCooperationAllowed(1);
        control.setRejectSearch(0);
        control.setRegionRejectSearch(0);
        control.setRejectTop(1);
        control.setRejectRecommend(1);
        control.setLiveDelayTime(0);
        control.setIpSegmentDelayTime(0);
        control.setAvailableStatus(1);
        control.setAddTime(new Timestamp(currentTime));
        control.setUpdateTime(new Timestamp(currentTime));
        control.setBlacklist("");
        return control;
    }

    private void doCreateDefaultPlatformControls(long channelId, boolean isFree) {
        List<PlatformControl> platformControls = new ArrayList<PlatformControl>();
        List<ChannelConfig> configList = channelService.getConfig("PlayPlatform");
        long currentTime = System.currentTimeMillis();
        PlatformControl control = null;
        if (isFree) {
            for (ChannelConfig channelConfig : configList) {
                control = createDefault(channelId, channelConfig.getKey(), currentTime);
                platformControls.add(control);
            }
        } else {
            for (Integer platKey : platforms) {
                control = createDefault(channelId, platKey, currentTime);
                platformControls.add(control);
            }
        }
        boolean flag = broadcastControlService.sets(channelId, platformControls);
        String detail = flag ? "操作成功" : "操作失败";
        writeChannelLog(channelId, Constants.LogType.AUTO_ALL_ONLINE.getIndex(), detail + "|isFree:" + isFree);

    }

    private void updateOffControls(long channelId) {
        updateCurrentControls(channelId, false);
    }

    private void updateOnlineControls(long channelId) {
        updateCurrentControls(channelId, true);
    }

    private void updateCurrentControls(long channelId, boolean online) {
        logger.info("[updateCurrentControls][channelId={}][online={}]", channelId, online);
        int type = online ? Constants.LogType.AUTO_ONLINE.getIndex() : Constants.LogType.AUTO_OFFLINE.getIndex();
        int status = online ? PlatformControl.AVAILABLE_STATUS_ALLOW : PlatformControl.AVAILABLE_STATUS_DENY;
        List<PlatformControl> list = broadcastControlService.getPlatformControls(channelId);
        List<Integer> platIds = new ArrayList<Integer>();
        for (PlatformControl platformControl : list) {
            platformControl.setAvailableStatus(status);
            platIds.add(platformControl.getPlayPlatform());
        }
        boolean flag = broadcastControlService.sets(channelId, list);
        String detail = flag ? "操作成功" : "操作失败";
        writeChannelLog(channelId, type, detail + ";platforms:" + platIds.toString());
    }


    private void doSystemDeleteChannel(ChannelBase channelBase) {
        String url = "http://localhost:8500/channel/del";
        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put("Sign", "#f93Uc31K24()_@");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("id", "" + channelBase.getId());
        JSONObject json = ApiHttpRequestUtil.postMethod(url, headers, params);
        String detailMsg = null;
        if (json != null) {
            if (Constants.CODE_SUC.equals(json.get("code"))) {
                sendDeleteReportSucMail(channelBase);
                detailMsg = json.getString("msg");
            } else {
                sendDeleteReportFailMail(channelBase, json.getString("msg"));
                detailMsg = "删除失败,错误原因：" + json.getString("msg");
            }
        } else {
            sendRequestReportFailMail(channelBase);
            detailMsg = "删除失败,错误原因：删除频道请求失败";
        }
        writeChannelLog(channelBase.getId(), Constants.LogType.AUTO_DELETE_CHANNEL.getIndex(), detailMsg);
    }

    private void doSystemDeleteStream(ChannelBase channelBase) {
        logger.info("[AutoBroadCastControlTrigger][doSystemDeleteStream][start][channelId={}]", channelBase.getId());
        String code = null;
        try {
            List<LiveChannelStream> liveChannelStreams = liveChannelStreamService.getByFatherId(channelBase.getId());
            for (LiveChannelStream liveChannelStream : liveChannelStreams) {
                liveStreamService.deleteQipu(liveChannelStream.getId(), channelBase.getId(), liveChannelStream.getStreamName(), null, liveChannelStream.getStreamApiVersion());
                liveChannelStreamService.delete(liveChannelStream);
            }
            code = Constants.CODE_SUC;
        } catch (Exception e) {
            logger.error("[AutoBroadCastControlTrigger][doSystemDeleteStream][Exception={}]", e);
            code = Constants.CODE_ERROR;
        } finally {
            logger.info("[AutoBroadCastControlTrigger][doSystemDeleteStream][End][Return:code={},codeValue={}]", new Object[]{code, Constants.getCode(code)});
        }
        writeChannelLog(channelBase.getId(), Constants.LogType.AUTO_SYSTEM_DELETE_STREAM.getIndex(), "channelId:" + channelBase.getId() + ";code:" + code);
    }

    private void doSendReindMail(ChannelBase channelBase, int restDay) {
        MailRemind mailRemind = mailRemindService.getMailRemind("Auto_Delete_RemindMail", channelBase.getId() + "");
        Timestamp endRange = mailRemind.getEndTime();
        Timestamp now = new Timestamp(System.currentTimeMillis());
        if (endRange != null && now.before(endRange)) {
            return;
        }
        if (endRange == null) {
            endRange = new Timestamp(now.getTime() + DateTimeUtil.DAY_TIME);
        } else {
            endRange = new Timestamp(endRange.getTime() + DateTimeUtil.DAY_TIME);
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put(MailConstant.C_NAME, channelBase.getName());
        map.put(MailConstant.C_QIPU_ID, channelBase.getQipuId() + "");
        map.put(MailConstant.C_ID, "" + channelBase.getId());
        map.put("day", restDay + "");
        notifyMailService.addMailAsyncTask(MailConstant.TOS_TYPE_P_MAIL_TYPE, MailContentUtil.ContentType.LS_AUTO_DEL_REMIND.getTypeIndex(), map);
        mailRemindService.saveMailHistory(mailRemind, MailContentUtil.ContentType.LS_AUTO_DEL_REMIND.toString(), "", "", endRange);
    }


    private void sendRequestReportFailMail(ChannelBase channelBase) {
        Map<String, String> map = new HashMap<String, String>();
        map.put(MailConstant.C_NAME, channelBase.getName());
        map.put(MailConstant.C_QIPU_ID, channelBase.getQipuId() + "");
        map.put(MailConstant.C_ID, "" + channelBase.getId());
        notifyMailService.addMailAsyncTask(MailConstant.TOS_TYPE_P_MAIL_TYPE + MailConstant.TOS_TYPE_FROM_LOG, MailContentUtil.ContentType.LS_DEL_REQUEST_FAIL.getTypeIndex(), map);
    }

    private void sendDeleteReportSucMail(ChannelBase channelBase) {
        Map<String, String> map = new HashMap<String, String>();
        map.put(MailConstant.C_NAME, channelBase.getName());
        map.put(MailConstant.C_QIPU_ID, channelBase.getQipuId() + "");
        map.put(MailConstant.C_ID, "" + channelBase.getId());
        notifyMailService.addMailAsyncTask(MailConstant.TOS_TYPE_P_MAIL_TYPE + MailConstant.TOS_TYPE_FROM_LOG, MailContentUtil.ContentType.LS_DEL_SUC.getTypeIndex(), map);
    }

    private void  doSendStreamEncodeMail(ChannelBase channelBase, String msg){
        Map<String, String> map = new HashMap<String, String>();
        map.put(MailConstant.C_NAME, channelBase.getName());
        map.put(MailConstant.C_QIPU_ID, channelBase.getQipuId() + "");
        map.put(MailConstant.C_ID, "" + channelBase.getId());
        map.put("msg", msg);
        notifyMailService.addMailAsyncTask(MailConstant.TOS_TYPE_P_MAIL_TYPE + MailConstant.TOS_TYPE_FROM_LOG, MailContentUtil.ContentType.LS_DEL_STREAM_FAIL_REMIND.getTypeIndex(), map);
    }

    private void sendDeleteReportFailMail(ChannelBase channelBase, String msg) {
        Map<String, String> map = new HashMap<String, String>();
        map.put(MailConstant.C_NAME, channelBase.getName());
        map.put(MailConstant.C_QIPU_ID, channelBase.getQipuId() + "");
        map.put(MailConstant.C_ID, "" + channelBase.getId());
        map.put("msg", msg);
        notifyMailService.addMailAsyncTask(MailConstant.TOS_TYPE_P_MAIL_TYPE + MailConstant.TOS_TYPE_FROM_LOG, MailContentUtil.ContentType.LS_DEL_FAIL_REMIND.getTypeIndex(), map);
    }

    private void checkDeleteRemind(long checkTime, ChannelBase channelBase, List<ProgramData> programDataList) {
        ProgramData lastOne = programDataList.get(programDataList.size() - 1);
        if (lastOne.getStopPlayTime().getTime() > checkTime) {
            return;
        }
        int betDays = Long.valueOf((checkTime - lastOne.getStopPlayTime().getTime()) / DateTimeUtil.DAY_TIME).intValue();
        int deleteDay = Long.valueOf(
                (channelBase.getCyclical() == 1 ? DELETE_GAP_TIME : DELETE_NONCYCLIAL_GAP_TIME) / DateTimeUtil.DAY_TIME)
                .intValue();
        int remindDay = deleteDay - 3;
        if (remindDay < 0) {
            remindDay = 0;
        }
        if (betDays >= deleteDay) {
            doSystemDeleteChannel(channelBase);
        } else if (betDays >= remindDay) {
            doSendReindMail(channelBase, deleteDay - betDays);
        }
    }

    private void writeChannelLog(long channelId, int type, String descr) {
        ChannelLog channelLog = new ChannelLog();
        channelLog.setFatherId(channelId);
        channelLog.setType(type);
        channelLog.setDescr(descr);
        channelLog.setUser(Constants.SYSTEM_USER_SIGN);
        channelService.saveLog(channelLog);
    }
}
